using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using CrushGame.DelegateSpace;

namespace CrushGame
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class TheCrushGame : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager _graphics;
        SpriteBatch _spriteBatch;
        ObjectManager _objManager;

        /// <summary>
        /// Previous keyboard state
        /// </summary>
        KeyboardState _prevState;

        //Game-Specific Modules
        public TheCrushGame()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // Initialize object manager
            _objManager = new ObjectManager();

            //subscribe to obj events
            _objManager.PlayerHasSpawned += new PlayerSpawnedHandler(PlayerSpawned);

            //Here we would run spawn script, but for now just spawn the player and a thing
            _objManager.Spawn<Player>(Content, new Vector2(250.0f, 250.0f), new Vector2(5.0f, -10.0f));
            _objManager.Spawn<Thing>(Content);
            
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            //Load Sprite Assets outside of objects
            
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            //Input Query
            InputQuery();

            //Calculate the float of Deltatime first
            float DeltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

            // Update objects
            _objManager.Update(DeltaTime);

            //Commented out because these objects no longer exist, and needs to play nice with the Obj manager
            //// TODO: Check for collisions here
            //// Move this process to the ObjectManager later.
            //Vector2 hitZone = new Vector2();
            //Vector2 hitZoneSize = new Vector2();

            //if (ThePlayer.Hitbox.CollidesWith(RandomDude.Hitbox, ref hitZone, ref hitZoneSize))
            //{
            //    if (hitZoneSize.X > hitZoneSize.Y)
            //    {
            //        //push the player vertically
            //        if (ThePlayer.Location.Y < RandomDude.Location.Y)
            //            ThePlayer.Location = new Vector2(ThePlayer.Location.X, ThePlayer.Location.Y - hitZoneSize.Y);
            //        else
            //            ThePlayer.Location = new Vector2(ThePlayer.Location.X, ThePlayer.Location.Y + hitZoneSize.Y);
            //    }
            //    else
            //    {
            //        // push horizontally
            //        if (ThePlayer.Location.X < RandomDude.Location.X)
            //            ThePlayer.Location = new Vector2(ThePlayer.Location.Y, ThePlayer.Location.X - hitZoneSize.X);
            //        else
            //            ThePlayer.Location = new Vector2(ThePlayer.Location.Y, ThePlayer.Location.X + hitZoneSize.X);
            //    }

            //    //ThePlayer.Velocity = ThePlayer.Velocity *= -1.0f;
            //}
            //// END collision handling

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            //Start the batching
            _spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

            // Draw Objects here
            _objManager.Draw(_spriteBatch);

            //End the batching
            _spriteBatch.End();

            base.Draw(gameTime);
        }

        void PlayerSpawned(object Sender, PlayerSpawnedEventArgs e)
        {
            //It is like making a temp pointer. This is for readability's sake more than anything
            Controller NewController;

            //Give the controller a reference to the game so it can sign up for input events
            NewController = new Controller(this, e.NewPlayer);

            //Assign it, and forget it
            e.NewPlayer.Controller = NewController;

        }

        /// <summary>
        /// Polls the keyboard and sends proper input events to the controllers that need to know
        /// </summary>
        protected void InputQuery()
        {
            //Start by snagging our current state
            KeyboardState CurrState = Keyboard.GetState();

            if (CurrState.IsKeyDown(Keys.W))
            {
                InputDetected(this, new InputEventArgs(InputCommand.CMD_Move_Up, (_prevState.IsKeyDown(Keys.W))));
            }

            if (CurrState.IsKeyDown(Keys.A))
            {
                InputDetected(this, new InputEventArgs(InputCommand.CMD_Move_Left, (_prevState.IsKeyDown(Keys.A))));
            }

            if (CurrState.IsKeyDown(Keys.S))
            {
                InputDetected(this, new InputEventArgs(InputCommand.CMD_Move_Down, (_prevState.IsKeyDown(Keys.S))));
            }

            if (CurrState.IsKeyDown(Keys.D))
            {
                InputDetected(this, new InputEventArgs(InputCommand.CMD_Move_Right, (_prevState.IsKeyDown(Keys.D))));
            }

            //Save it out now that we are done. It is officially a Previous state
            _prevState = CurrState;
        }

        /// <summary>
        /// Event to send when input happens, and is buffered.
        /// </summary>
        public event InputEventHandler InputDetected;
    }
}
